import subprocess
import time


def run_adb_command(ip, port, command_args):
    connect_command = f'adb connect {ip}:{port}'

    """运行ADB命令"""
    base_command = ['adb', '-s', f'{ip}:{port}']
    full_command = base_command + command_args
    try:
        subprocess.run(connect_command, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
        result = subprocess.run(full_command, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
        return result
    except subprocess.CalledProcessError as e:
        print("An error occurred:", e.stderr)

def check_app_installed(ip, port, package_name):
    try:
        # 使用 adb 命令检查应用程序包是否已安装
        result = run_adb_command(ip, port, ["shell", "pm", "list", "packages", package_name])
        # 检查输出是否包含指定的包名
        return package_name in result.stdout
    except subprocess.CalledProcessError as e:
        print(f"错误: 无法检查应用程序是否安装: {e}")
        return None

def install_dtpk(device_ip, device_port):
    #崩坏3
    # package_name = 'com.miHoYo.bh3.uc'
    # app_path = r'C:\Users\chao\Desktop\benghuai3.apk'

    #抖音
    package_name = "com.ss.android.ugc.aweme"
    app_path = "/Users/wancongpeng/Downloads/apk/douyin.apk"

    #王者荣耀
    #package_name = 'com.tencent.tmgp.sgame'
    #app_path = r'C:\Users\chao\Desktop\wangzhe.apk'

    if is_app_install(device_ip, device_port, package_name):
        print('设备已安装，无需安装')
        return
    else:
        print("Installing the app...")
        start = time.time()
        run_adb_command(device_ip, device_port, ['install', app_path])
        end = time.time()
        print("安装时间:%.2f秒"%(end-start))


def is_app_install(device_ip, device_port, package_name):
    return check_app_installed(device_ip, device_port, package_name)


if __name__ == '__main__':
    #安卓ip地址
    ip = "60.28.168.125"
    #安卓ip端口号
    port_list = [
        "20446"
    ]
    for port in port_list:
        print("端口为", port)
        install_dtpk(ip, port)
        print('-----------------------------------------------')
